<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <script src="/js/vue.js"></script>
    <script src="/js/axios.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="/js/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="/js/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
    <el-button type="primary" @click="delBatch">批量删除</el-button>
    <el-button type="success" @click="add">添加</el-button>

    <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange">
        <el-table-column
                type="selection"
                width="55">
        </el-table-column>
        <el-table-column
                prop="id"
                label="用户编号"
                width="120">
        </el-table-column>
        <el-table-column
                prop="name"
                label="姓名"
                width="120">
        </el-table-column>
        <el-table-column
                prop="age"
                label="年龄"
                width="120">
        </el-table-column>

        <el-table-column label="操作">
            <template slot-scope="scope">
                <el-button
                        size="mini"
                        @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>


    <!--添加活修改弹出框-->
    <el-dialog title="用户管理" :visible.sync="dialogFormVisible">
        <el-form :model="form">
            <el-form-item label="用户姓名" :label-width="formLabelWidth">
                <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="年龄" :label-width="formLabelWidth">
                <el-input v-model="form.age" autocomplete="off"></el-input>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="edit">确 定</el-button>
        </div>
    </el-dialog>


</div>

<script>
    new Vue({
        el: "#app",
        data() {
            return {
                tableData: [],
                multipleSelection: [],
                dialogFormVisible: false,
                form: {
                    name: '',
                    age:''
                },
                formLabelWidth: '120px'
            }
        },
        methods: {
            loadUser() {
                // 发送异步请求，查询全部用户
                // resp 封装的是控制器返回的对象转换为json后，经过axios封装的数据
                axios.get('/user').then(resp => {
                    console.log('resp:', resp);
                    // 根据后台返回的数据，赋值给tableData，再由elementui显示表格
                    this.tableData = resp.data;
                })
            },
            // 当列表复选框发送变化时候触发
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 进入修改页面（回显数据）
            handleEdit(index, row) {
                console.log(index, row);
                // 数据回显
                //this.form = row; // 问题：修改页面修改数据，列表跟着变化。

                // 对象转换为json字符串
                let userString = JSON.stringify(row);
                // 字符串转换为json对象
                let userObj = JSON.parse(userString);
                // 赋值
                this.form = userObj;

                // 弹出一个页面 el-dialog
                this.dialogFormVisible = true;
            },
            handleDelete(index, row) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 点击确认, 先删除
                    axios.delete(`/user/${row.id}`).then(resp=>{
                        // 删除后重新加载列表
                        this.loadUser();
                    })
                    // 再提示用户
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            delBatch(){
                // 获取复选框值
                // this.multipleSelection=[{id:100,name:jack,age:10},{}]
                console.log('选中的数据：',this.multipleSelection);

                // 判断
                if (this.multipleSelection.length == 0) {
                    this.$message.error('请先选中行，再删除！');
                    return;
                }
                // 保存选中行的id
                // let ids = new Array();
                // //let ids = [];
                // for(let i=0; i<this.multipleSelection.length;i++) {
                //     //ids.push(this.multipleSelection[i].id);
                //     ids[i] = this.multipleSelection[i].id;
                // }
                // console.log(ids);

                // a = {id:100,name:jack,age:10}
                let ids = this.multipleSelection.map(a=>a.id);
                console.log(ids);

                // 请求后台，批量删除 (如果发送的是delete请求，没有请求体的，后台无法通过@RequestBody获取参数)
                axios.put('/user/del/batch',ids).then(resp=>{
                    // 删除后重新加载列表
                    this.loadUser();
                })
            },

            // 添加或修改方法
            edit(){
                axios.post('/user',this.form).then(resp=>{
                    if (resp.data) {
                        // 重新加载列表
                        this.loadUser();
                    }
                })
                this.dialogFormVisible = false
            },
            // 点击添加按钮，弹框
            add(){
                //this.form.id = ''
                //this.form.name = ''
                //this.form.age = ''
                this.form= {}
                this.dialogFormVisible = true;
            }

        },

        created() {
            this.loadUser();
        }
    })
</script>
</body>
</html>